package com.springmvc.way;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by 29047 on 2017/12/26.
 */
//上传、保存文件函数
public class Msfile {

    private MultipartFile[] files;
    private MultipartFile file;
    private HttpServletRequest request;

    public Msfile(MultipartFile[] files,HttpServletRequest request){
        this.files = files;
        this.request = request;
    }
    public Msfile(MultipartFile file,HttpServletRequest request){
        this.file = file;
        this.request = request;
    }

    //获取文件地址函数
    public String strPic(){
        String strPic = null;
        if(files!=null&&files.length>0){
            //循环获取file数组中得文件
            for(int i = 0;i<files.length;i++){
                this.file = files[i];
                //保存文件
                if(strPic == null){
                    strPic =saveFile();
                }else{
                    strPic += "|"+saveFile();
                }
            }
        }
        return strPic;
    }
    //保存文件函数
    public String saveFile() {
        String purl = null;
        //判断文件是否为空
        if (!file.isEmpty()){
            try {
                String fileName = file.getOriginalFilename();//设置文件名
                //文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("images")+File.separator+fileName;
                //转存文件
                file.transferTo(new File(filePath));
                //return true;
                purl = "images\\"+fileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return purl;
    }
}
